package redis_func

import (
	"fmt"
	"github.com/go-redis/redis"
	"log"
	"sdapiproject/utils"
)

var Client *redis.Client

const (
	TXT2IMG_TASK   = "txt2img_task"
	TXT2IMG_STATUS = "txt2img_status"
	PROCESSING     = 2 // 正在生成
	FAILED         = 3 // 生成失败
	SUCCESS        = 4 // 生成成功
	CANCEL         = 5 // 取消
	QUEUED         = 6 // 排队中
)

func Init() {

	cfg, err := utils.LoadConfig()
	if err != nil {
		log.Fatalf("Error loading config: %v", err)
	}

	Client = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", cfg.Redis.HOST, cfg.Redis.Port),
		Password: cfg.Redis.Password, // no password set
		DB:       cfg.Redis.Database, // use default DB
	})
}

// 把任务存进hash表

func SetTxt2ImgTaskToRedis(taskId string, data string) error {
	err := Client.HSet(TXT2IMG_TASK, taskId, data).Err()
	if err != nil {
		return err
	}
	return nil
}

func GetTxt2ImgTaskFromRedis(taskId string) (string, error) {
	data, err := Client.HGet(TXT2IMG_TASK, taskId).Result()
	if err != nil {
		return "", err
	}
	return data, nil
}

func SetTxt2ImgStatusToRedis(taskId string, status int) error {
	err := Client.HSet(TXT2IMG_STATUS, taskId, status).Err()
	if err != nil {
		return err
	}
	return nil
}

func GetTxt2ImgStatusFromRedis(taskId string) (int, error) {
	status, err := Client.HGet(TXT2IMG_STATUS, taskId).Int()
	if err != nil {
		return 0, err
	}
	return status, nil
}
